/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * DeRmPanel.java
 *
 * Created on 27/11/2011, 21:16:10
 */
package proj5labbd.graphics.departamento;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import proj5labbd.DBInterface;
import proj5labbd.graphics.abstractOpGraphics.OperationPanel;

/*
 * Painel de remoção de departamentos
 */
public class DeRmPanel extends OperationPanel {

    /** Creates new form DeRmPanel */
    public DeRmPanel(DeptFrame frame, DBInterface dbInterface) {
        super(frame,dbInterface);
        initComponents();
        jbtRemove.addActionListener(new DeptAction());
        addComponentListener( new java.awt.event.ComponentAdapter() {
                public void componentShown(java.awt.event.ComponentEvent evt) {
                    formComponentShown(evt);
                }
        });
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jpnParam = new javax.swing.JPanel();
        jlbNome = new javax.swing.JLabel();
        jftxtTel = new javax.swing.JFormattedTextField();
        jlbTel = new javax.swing.JLabel();
        jtxtNome = new javax.swing.JTextField();
        jlbEm = new javax.swing.JLabel();
        jlbNFunc = new javax.swing.JLabel();
        jtxtNFunc = new javax.swing.JTextField();
        jftxtEm = new javax.swing.JFormattedTextField();
        jbtRemove = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jtbRemove = new javax.swing.JTable();

        setBorder(javax.swing.BorderFactory.createTitledBorder("Remoção"));
        addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                formMouseClicked(evt);
            }
        });
        addComponentListener(new java.awt.event.ComponentAdapter() {
            public void componentShown(java.awt.event.ComponentEvent evt) {
                formComponentShown(evt);
            }
        });

        jpnParam.setBorder(javax.swing.BorderFactory.createTitledBorder("Parâmetros da busca"));

        jlbNome.setText("Nome");

        try {
            jftxtTel.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##########")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        jftxtTel.setFocusLostBehavior(javax.swing.JFormattedTextField.COMMIT);

        jlbTel.setText("Telefone");

        jlbEm.setText("Emissora (CNPJ)");

        jlbNFunc.setText("Nro. de Funcionários");

        try {
            jftxtEm.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.MaskFormatter("##.###.###/####-##")));
        } catch (java.text.ParseException ex) {
            ex.printStackTrace();
        }
        jftxtEm.setFocusLostBehavior(javax.swing.JFormattedTextField.COMMIT);

        javax.swing.GroupLayout jpnParamLayout = new javax.swing.GroupLayout(jpnParam);
        jpnParam.setLayout(jpnParamLayout);
        jpnParamLayout.setHorizontalGroup(
            jpnParamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpnParamLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jpnParamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jftxtEm)
                    .addComponent(jlbNome, javax.swing.GroupLayout.PREFERRED_SIZE, 83, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jtxtNome, javax.swing.GroupLayout.DEFAULT_SIZE, 196, Short.MAX_VALUE)
                    .addComponent(jlbEm))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jpnParamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jlbNFunc)
                    .addComponent(jlbTel)
                    .addComponent(jftxtTel, javax.swing.GroupLayout.DEFAULT_SIZE, 194, Short.MAX_VALUE)
                    .addComponent(jtxtNFunc))
                .addContainerGap(36, Short.MAX_VALUE))
        );
        jpnParamLayout.setVerticalGroup(
            jpnParamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jpnParamLayout.createSequentialGroup()
                .addGroup(jpnParamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jpnParamLayout.createSequentialGroup()
                        .addComponent(jlbTel)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jftxtTel, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(jpnParamLayout.createSequentialGroup()
                        .addComponent(jlbNome)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jtxtNome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jpnParamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jlbEm)
                    .addComponent(jlbNFunc))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jpnParamLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jtxtNFunc, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jftxtEm, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jbtRemove.setText("Remover");

        jtbRemove.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {

            }
        ));
        jScrollPane1.setViewportView(jtbRemove);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jbtRemove, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 462, Short.MAX_VALUE)
                            .addComponent(jpnParam, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                        .addContainerGap())))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jpnParam, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 393, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jbtRemove))
        );
    }// </editor-fold>//GEN-END:initComponents

    //ação desencadeada no evento do click do mouse no painel
    private void formMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_formMouseClicked
        // TODO add your handling code here:
        jtbRemove.clearSelection();
    }//GEN-LAST:event_formMouseClicked

    //ação desencadeadao à apresentação do painel ao usuário
    private void formComponentShown(java.awt.event.ComponentEvent evt) {//GEN-FIRST:event_formComponentShown
        // TODO add your handling code here:
        setupTable();
    }//GEN-LAST:event_formComponentShown

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JButton jbtRemove;
    private javax.swing.JFormattedTextField jftxtEm;
    javax.swing.JFormattedTextField jftxtTel;
    private javax.swing.JLabel jlbEm;
    private javax.swing.JLabel jlbNFunc;
    private javax.swing.JLabel jlbNome;
    private javax.swing.JLabel jlbTel;
    private javax.swing.JPanel jpnParam;
    private javax.swing.JTable jtbRemove;
    private javax.swing.JTextField jtxtNFunc;
    javax.swing.JTextField jtxtNome;
    // End of variables declaration//GEN-END:variables

    //configuração da(s) tabela(s) a partir de dados resgatados da base de dados
    private void setupTable() {
        try {
            // TODO add your handling code here:
            String[] fields = {"idDe", "nomeDe", "telefoneDe", "nroFuncionariosDe", "cnpjEm"};
            String[][] s = dbInterface.view(fields, null, new String[]{"departamento"});
            DefaultTableModel modelIn = new DefaultTableModel(s, new String[]{"ID", "Nome do departamento","Telefone"
                        ,"Nro de funcionários","Emissora (CNPJ)"});
            jtbRemove.setModel(modelIn);
            jtbRemove.setRowSelectionAllowed(true);
        } catch (SQLException ex) {
            frame.printException(ex);
            JOptionPane.showMessageDialog(null,"Erro ao buscar os dados de departamento no banco de dados.");
        }
    }
    //ouvinte dos eventos do botão de remoção
    class DeptAction implements ActionListener {
        //ação do botão de remoção
        public void actionPerformed(ActionEvent e) {
            
            if (e.getSource() == jbtRemove) {

                ArrayList<String> param = new ArrayList<String>();

                if (jftxtEm.getText().compareTo("  .   .   /    -  ") != 0) {
                param.add("UPPER(departamento.cnpjEm)=UPPER('"+jftxtEm.getText()+"')");
                }
                if (jftxtTel.getText().compareTo("          ") != 0) {
                    param.add("departamento.telefoneDe="+jftxtTel.getText());
                }
                if (jtxtNFunc.getText().compareTo("") != 0) {
                    param.add("departamento.nroFuncionariosDe="+jtxtNFunc.getText());
                }
                if (jtxtNome.getText().compareTo("") != 0) {
                    param.add("UPPER(departamento.nomeDe)=UPPER('"+jtxtNome.getText()+"')");
                }

                if (param.size() > 0) {
                    try {
                        String[] paramArray = new String[param.size()];
                        param.toArray(paramArray);
                        dbInterface.remove(paramArray, new String[]{"departamento"});
                    } catch (SQLException ex) {
                        frame.printException(ex);
                        JOptionPane.showMessageDialog(null, "Erro ao remover as tuplas desejadas.");
                    }
                } else {

                    if (jtbRemove.getSelectedRowCount() != 1) {
                    JOptionPane.showMessageDialog(null, "Você deve selecionar apenas uma linha da tabela.");
                    }
                    else if (jtbRemove.getSelectedRowCount() == 1) {
                        try {
                            String[] params = new String[1];
                            params[0] = "idDe=" + jtbRemove.getValueAt(jtbRemove.getSelectedRow(), 0);
                            dbInterface.remove(params, new String[]{"departamento"});
                        } catch (SQLException ex) {
                            frame.printException(ex);
                            JOptionPane.showMessageDialog(null, "Erro ao tentar remover a tupla.");
                        }
                    }
                    else if (jtbRemove.getSelectedRowCount() == 0) {
                        JOptionPane.showMessageDialog(null, "Você deve escolhar uma tupla ou um parâmetro para a remoção.");
                    }

                }
                
                setupTable();
                
            }
            
        }
        
    }
}
